package com.zxy.leetcode._00000_00099._00010_00019;

/**
 * https://leetcode-cn.com/problems/longest-common-prefix/
 * 最长公共前缀
 *
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀，返回空字符串 ""。
 */
public class Test00014 {

    public static void main(String[] args) {
        Test00014 test = new Test00014();

        String[] strs1 = {"flower","flow","flight"};
        System.out.println(test.longestCommonPrefix(strs1));

        String[] strs2 = {"dog","racecar","car"};
        System.out.println(test.longestCommonPrefix(strs2));
    }

    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        if (strs.length == 1) {
            return strs[0];
        }

        int count = -1;
        boolean again = true;
        for (int i=0; i<strs[0].length()&&again; i++) {
            for (int j=1; j<strs.length; j++) {
                if (i >= strs[j].length()) {
                    again = false;
                    break;
                }
                if (strs[0].charAt(i) != strs[j].charAt(i)) {
                    again = false;
                    break;
                }
            }
            if (again) {
                count = i;
            }
        }

        if (count < 0) {
            return "";
        }

        return strs[0].substring(0, count+1);
    }

}
